namespace SimpleTPL.AutoGen;

// 模拟编译器生成的状态机
class GetAnswerAsyncStateMachine : IAsyncStateMachine
{
    public int State;
    public SimpleAsyncMethodBuilder<int> Builder;
    private SimpleTaskAwaiter _awaiter;
    private int _result;

    public void MoveNext()
    {
        try
        {
            switch (State)
            {
                case 0:
                    Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] GetAnswerAsyncStateMachine state 0");
                    
                    var delayTask = SimpleTask.Delay(1000);
                    _awaiter = delayTask.GetAwaiter();
                    
                    if (!_awaiter.IsCompleted)
                    {
                        State = 1;
                        // 现在可以安全传递 this 引用
                        Builder.AwaitOnCompleted(ref _awaiter, this);
                        return;
                    }
                    goto case 1;
                
                case 1:
                    Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] GetAnswerAsyncStateMachine state 1");
                    
                    _awaiter.GetResult();
                    _awaiter = default;
                    _result = 100;
                    Builder.SetResult(_result);
                    
                    Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] Result={_result} ");
                    
                    break;
            }
        }
        catch (Exception ex)
        {
            Builder.SetException(ex);
        }
    }
}